<template>
  <div class="wrapper">
    <!-- 薪酬变化趋势 -->
    <el-row class="search-container">
      <el-form ref="form" label-width="auto">
        <el-form-item label="统计时间：">
          <el-date-picker
            v-model="selectBetweenTime"
            size="small"
            type="monthrange"
            :clearable="false"
            align="right"
            unlink-panels
            value-format="yyyy-MM-dd"
            range-separator="-"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            :picker-options="pickerOptions"
            @change="handleDateChange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="区域名称：">
          <multipleRegoinSearch
            ref="regionRef"
            :limitNum="limitNum"
            @onRegionChange="onRegionChange"
          />
        </el-form-item>
      </el-form>
    </el-row>
    <div class="chartMain">
      <template v-if="chartDataIsNotEmpty">
        <div class="h100" ref="line_echartDom" id="line_echartDom"></div>
        <!-- <div class="regionLineDesc">
          <div
            class="regionLineDescItem"
            v-for="(item, index) in chartData.averageSalaryList"
            :key="index"
          >
            <div class="descTitle">{{ item.name }}约</div>
            <div class="descNum">
              <span class="rmb">￥</span>{{ item.value }}/<span class="rmb"
                >月</span
              >
            </div>
          </div>
        </div> -->
      </template>
      <el-empty class="empty" description="暂无数据" v-else>
        <el-button type="primary" size="mini" @click="handleKnowClick()">
          想要了解
        </el-button>
      </el-empty>
    </div>
  </div>
</template>

<script>
import { chartRegionSalary, reportLackDataPosition } from "@/api/salary";
import multipleRegoinSearch from "@/views/position/components/multipleRegoinSearch.vue";
export default {
  name: "regionLineChart",
  components: {
    multipleRegoinSearch,
  },
  data() {
    return {
      maxY: 20000,
      limitNum: 3,
      resData: [],
      chartData: {},
      selectBetweenTime: [],
      firstDayofLastMonth: "",
      chartDataIsNotEmpty: true, //必须让图表先显示，不然会出现空白
      pickerMinDate: "",
      pickerOptions: {
        disabledDate: (time) => {
          const nowTime = time.getTime();
          if (nowTime < 1672502400000 || nowTime > this.firstDayofLastMonth) {
            return true;
          }
          if (this.pickerMinDate) {
            const monthsDiff =
              Math.abs(nowTime - this.pickerMinDate) /
              (1000 * 60 * 60 * 24 * 30);
            // 如果相差的月份大于6个月，则禁用该日期
            return monthsDiff > 7 || nowTime < 1672502400000;
          }
        },
        onPick: (obj) => {
          this.pickerMinDate = new Date(obj.minDate).getTime();
        },
      },
      average: "",
      selectedRegionList: [],
      regionLineDescAvg: "",
      isSetDeaultTime: false,
      isSetDeaultRegion: true,
      // averageSalaryList:[],// 平均薪酬数组
    };
  },
  created() {
    // 创建一个表示当前日期的 Date 对象
    var currentDate = new Date();

    // 将当前日期设置为本月的第一天
    currentDate.setDate(1);

    // 将当前日期减去一天，得到上个月最后一天
    currentDate.setDate(0);

    // 设置时间为零点
    currentDate.setHours(0, 0, 0, 0);

    // 获取时间戳
    var timestamp = currentDate.getTime();

    this.firstDayofLastMonth = timestamp;
  },
  mounted() {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let newYear = 0;
    let newMonth = 0;
    let newDateArr = [];
    for (let i = 0; i < 7; i++) {
      //这里是获取前六个月,所以循环6次,根据需要修改
      if (month - i < 1) {
        //这里的判断是如果当前月份往前推到了去年  需要做的处理
        newYear = year - 1;
        newMonth =
          month - i + 12 >= 10 ? month - i + 12 : "0" + (month - i + 12);
        newDateArr.push(newYear + "-" + newMonth + "-" + "01"); //这里拼接格式化,在时间中间加了个-,根据实际需求来
      } else {
        newMonth = month - i >= 10 ? month - i : "0" + (month - i); //这里是对月份小于10做加前面加0处理
        newDateArr.push(year + "-" + newMonth + "-" + "01");
      }
    }
    //这里就最后得到当前年月前六个月组成的时间数组,根据需要赋值使用即可
    const end = newDateArr[1];
    const start = newDateArr[6];
    // this.isSetDeaultTime = true;
    this.selectBetweenTime = [start, end];
    // console.log(
    //   "this.selectBetweenTime---------->",
    //   this.selectBetweenTime,
    //   newDateArr
    // );

    this.fetchData();
  },
  methods: {
    fetchData() {
      // //console.log("this.selectedRegionList", this.selectedRegionList);

      this.listLoading = true;
      const params = {
        id: this.$route.query.id,
      };
      // params.beginTime = "2023-1-1";
      // params.endTime = "2023-5-1";
      if (this.selectBetweenTime != null && this.selectBetweenTime != "") {
        params.beginTime = this.selectBetweenTime[0];
        params.endTime = this.selectBetweenTime[1];
        // params.beginTime = "2023-1-1";
        // params.endTime = "2023-5-1";
      }
      params.regionIds = this.selectedRegionList.join("_");
      chartRegionSalary(params)
        .then((response) => {
          if (response.code == 200) {
            this.regionLineDescAvg = response.data.average;
            let regionList = [
              {
                value: "100000",
                label: "全国",
              },
              {
                value: "110000",
                label: "北京",
              },
              { value: "310000", label: "上海" },
              {
                value: "440100",
                label: "广州",
              },
              {
                value: "440300",
                label: "深圳",
              },
              {
                value: "510100",
                label: "成都",
              },
              { value: "500000", label: "重庆" },
              { value: "330100", label: "杭州" },
              { value: "610100", label: "西安" },
              {
                value: "420100",
                label: "武汉",
              },
              {
                value: "320500",
                label: "苏州",
              },
              { value: "410100", label: "郑州" },
              { value: "320100", label: "南京" },
              {
                value: "120000",
                label: "天津",
              },
              { value: "430100", label: "长沙" },
              { value: "441900", label: "东莞" },
              {
                value: "330200",
                label: "宁波",
              },
              { value: "440600", label: "佛山" },
              {
                value: "340100",
                label: "合肥",
              },
              { value: "370200", label: "青岛" },
              {
                value: "530100",
                label: "昆明",
              },
              {
                value: "210100",
                label: "沈阳",
              },
              {
                value: "370100",
                label: "济南",
              },
              {
                value: "320200",
                label: "无锡",
              },
              {
                value: "350200",
                label: "厦门",
              },
              {
                value: "350100",
                label: "福州",
              },
              {
                value: "330300",
                label: "温州",
              },
              {
                value: "330700",
                label: "金华",
              },
              {
                value: "230100",
                label: "哈尔滨",
              },
              {
                value: "210200",
                label: "大连",
              },
              {
                value: "520100",
                label: "贵阳",
              },
              {
                value: "450100",
                label: "南宁",
              },
              { value: "350500", label: "泉州" },
              {
                value: "130100",
                label: "石家庄",
              },
              { value: "220100", label: "长春" },
              { value: "360100", label: "南昌" },
              { value: "441300", label: "惠州" },
              { value: "320400", label: "常州" },
              { value: "330400", label: "嘉兴" },
              { value: "320300", label: "徐州" },
              { value: "320600", label: "南通" },
              { value: "140100", label: "太原" },
              { value: "130600", label: "保定" },
              { value: "440400", label: "珠海" },
              { value: "442000", label: "中山" },
              {
                value: "620100",
                label: "兰州",
              },
              {
                value: "371300",
                label: "临沂",
              },
              { value: "370700", label: "潍坊" },
              { value: "370600", label: "烟台" },
              { value: "330600", label: "绍兴" },
            ];
            // 将后端返回的数据中带城市的去掉最后的市比如杭州市 变成 杭州
            response.data.list.forEach((item, index) => {
              if (item.salaryRegionName.endsWith("市")) {
                item.salaryRegionName = item.salaryRegionName.substring(
                  0,
                  item.salaryRegionName.length - 1
                );
              }
            });
            console.log("response.data.list", response.data.list);

            // 创建一个映射对象，将地区名称映射到 regionList 中的索引
            let regionIndexMap = regionList.reduce((acc, region, index) => {
              acc[region.label] = index;
              return acc;
            }, {});
            // 使用映射对象对后端数据进行排序
            response.data.list.sort((a, b) => {
              return (
                regionIndexMap[a.salaryRegionName] -
                regionIndexMap[b.salaryRegionName]
              );
            });

            // 根据上面提供的地区regionList对response.data.list进行一个排序
            this.chartData = this.handleData(response.data.list);
            console.log("this.chartData", this.chartData);
            this.chartDataIsNotEmpty =
              response.data.list && response.data.list.length > 0;
            setTimeout(() => {
              this.init();
            }, 500);
          } else {
            this.chartDataIsNotEmpty = false;
          }
        })
        .catch(() => {
          this.chartDataIsNotEmpty = false;
        });
    },
    handleData(data) {
      let dataArr = {
        city: [],
        time: [],
        name: [],
        averageSalaryList: [],
      };

      if (data[data.length - 1]) {
        data[data.length - 1].salarys.forEach((item) => {
          dataArr.time.push(`${item.month}${item.year}`);
        });
      }

      dataArr.city = data.map((item) => {
        if (item) {
          dataArr.name.push(item.salaryRegionName);
          const maxSalary = [];
          const minSalary = [];
          const averageSalary = [];
          const middleSalary = [];

          item.salarys.forEach((item) => {
            // salaryNum是平均薪资
            // fiftyPercentile 中位数
            // ninetyFivePercentile 最高
            // tenPercentile 最低
            maxSalary.push(item.ninetyFivePercentile); // 最高薪资
            minSalary.push(item.tenPercentile); // 最低薪资
            averageSalary.push(item.salaryNum); // 平均薪资
            middleSalary.push(item.fiftyPercentile); // 中位数薪资
          });

          // 计算各个数组的平均值
          const calculateAverage = (arr) => {
            if (arr.length === 0) return 0;
            const sum = arr.reduce((acc, val) => acc + val, 0);
            return Number((sum / arr.length).toFixed(1));
          };

          // 将计算结果添加到 averageSalaryList
          dataArr.averageSalaryList = [
            {
              name: "平均平均薪资",
              value: calculateAverage(averageSalary),
            },
            {
              name: "平均最高薪资",
              value: calculateAverage(maxSalary),
            },
            {
              name: "平均中位数薪资",
              value: calculateAverage(middleSalary),
            },
            {
              name: "平均最低薪资",
              value: calculateAverage(minSalary),
            },
          ];

          return {
            name: item.salaryRegionName,
            maxSalary,
            minSalary,
            averageSalary,
            middleSalary,
          };
        }
      });

      return dataArr;
    },
    init() {
      if (!this.$refs["line_echartDom"]) {
        console.log(
          "------------------------this.$refs['line_echartDom'] is null"
        );
        return;
      }

      // 如果已存在实例，先销毁
      if (this.myChart) {
        this.myChart.dispose();
      }

      this.myChart = this.$echarts.init(this.$refs["line_echartDom"]);

      let data0 = [];
      let data1 = [];
      let data2 = [];
      // 这部分数据结构非常复杂
      // 盒须图想要去掉须要从数据结构入手
      // [min,min,min,max,max]按照这个结构去构建数据
      this.chartData.city.forEach((ele, index) => {
        this.chartData.city[index].minSalary.forEach((minitem) => {
          switch (index) {
            case 0:
              data0.push([minitem, minitem, minitem]);
              break;
            case 1:
              data1.push([minitem, minitem, minitem]);
              break;
            case 2:
              data2.push([minitem, minitem, minitem]);
              break;
            default:
              break;
          }
        });
        this.chartData.city[index].maxSalary.forEach((maxitem, _index) => {
          switch (index) {
            case 0:
              data0[_index].push(maxitem);
              data0[_index].push(maxitem);
              break;
            case 1:
              data1[_index].push(maxitem);
              data1[_index].push(maxitem);
              break;
            case 2:
              data2[_index].push(maxitem);
              data2[_index].push(maxitem);
              break;
            default:
              break;
          }
        });
      });

      let option = {
        dataset: [
          {
            source: data0,
          },
          {
            source: data1,
          },
          {
            source: data2,
          },
          {
            fromDatasetIndex: 0,
            transform: {
              type: "boxplot",
              config: {
                itemNameFormatter: (params) => {
                  switch (params.value) {
                    case 0:
                      return this.chartData.time[0];
                      break;
                    case 1:
                      return this.chartData.time[1];
                      break;
                    case 2:
                      return this.chartData.time[2];

                      break;
                    case 3:
                      return this.chartData.time[3];

                      break;
                    case 4:
                      return this.chartData.time[4];

                      break;
                    case 5:
                      return this.chartData.time[5];
                      break;
                    default:
                      return "ungrouped";
                    // code
                  }
                },
              },
            },
          },
          {
            fromDatasetIndex: 1,
            transform: {
              type: "boxplot",
              config: {
                itemNameFormatter: (params) => {
                  switch (params.value) {
                    case 0:
                      return this.chartData.time[0];
                      break;
                    case 1:
                      return this.chartData.time[1];
                      break;
                    case 2:
                      return this.chartData.time[2];
                      break;
                    case 3:
                      return this.chartData.time[3];
                      break;
                    case 4:
                      return this.chartData.time[4];

                      break;
                    case 5:
                      return this.chartData.time[5];
                      break;
                    default:
                      return "ungrouped";
                    // code
                  }
                },
              },
            },
          },
          {
            fromDatasetIndex: 2,
            transform: {
              type: "boxplot",
              config: {
                itemNameFormatter: (params) => {
                  switch (params.value) {
                    case 0:
                      return this.chartData.time[0];
                      break;
                    case 1:
                      return this.chartData.time[1];
                      break;
                    case 2:
                      return this.chartData.time[2];

                      break;
                    case 3:
                      return this.chartData.time[3];

                      break;
                    case 4:
                      return this.chartData.time[4];

                      break;
                    case 5:
                      return this.chartData.time[5];
                      break;
                    default:
                      return "ungrouped";
                    // code
                  }
                },
              },
            },
          },
        ],
        legend: {
          top: "10%",
        },
        tooltip: {
          trigger: "item",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          left: "10%",
          top: "20%",
          right: "10%",
          bottom: "15%",
        },
        xAxis: {
          type: "category",
          // data:['1','a','9月2024','10月2024'],
          boundaryGap: true,
          nameGap: 30,
          // data: this.chartData.time,
          splitArea: {
            show: true,
          },
          splitLine: {
            show: false,
          },
        },
        yAxis: {
          type: "value",
          name: "（薪酬 元）",
          min: 0,
          // max: this.maxY,
          splitArea: {
            show: false,
          },
        },
        dataZoom: [
          {
            type: "inside",
            start: 0,
            end: 100, // 修改这里
          },
          {
            show: true,
            type: "slider",
            top: "90%",
            xAxisIndex: [0],
            start: 0,
            end: 100, // 修改这里
          },
        ],
        series: [
          {
            name: "",
            type: "boxplot",
            datasetIndex: 3,
            boxWidth: "16px", // 设置箱体宽度为坐标轴宽度的 50%
            itemStyle: {
              normal: {
                // 配置箱体的样式
                color: {
                  type: "linearGradient",
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    { offset: 0, color: "rgba(255, 99, 132, 0.3)" }, // 0% 处的颜色
                    { offset: 1, color: "rgba(255, 99, 132, 0.7)" }, // 100% 处的颜色
                  ],
                  global: false, // 缺省为 false
                },
                borderColor: "rgba(255, 99, 132, 0.3)", // 箱体边框的颜色
                borderWidth: 1, // 箱体边框的宽度
              },
            },
            splitNumber: 1, // 控制箱体分割的数量，1 表示不分割，即不显示须
            tooltip: {
              formatter: function (param) {
                return [
                  "最高薪资: " + param.data[5],
                  "最低薪资: " + param.data[1],
                ].join("<br/>");
              },
            },
          },
          {
            name: "",
            type: "boxplot",
            datasetIndex: 4,
            boxWidth: "16px", // 设置箱体宽度为坐标轴宽度的 50%
            itemStyle: {
              normal: {
                color: {
                  type: "linearGradient",
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    { offset: 0, color: "rgba(54, 162, 235, 0.3)" }, // 0% 处的颜色
                    { offset: 1, color: "rgba(54, 162, 235, 0.7)" }, // 100% 处的颜色
                  ],
                  global: false, // 缺省为 false
                  borderRadius: [5, 5, 0, 0], // 设置左上角和右上角为圆角，底部为直角
                },
                borderColor: "rgba(54, 162, 235, 0.3)", // 箱体边框的颜色
                borderWidth: 1, // 箱体边框的宽度
              },
            },
            splitNumber: 1, // 控制箱体分割的数量
            tooltip: {
              formatter: function (param) {
                return [
                  "最高薪资: " + param.data[5],
                  "最低薪资: " + param.data[1],
                ].join("<br/>");
              },
            },
          },
          {
            name: "",
            type: "boxplot",
            datasetIndex: 5,
            boxWidth: "16px", // 设置箱体宽度为坐标轴宽度的 50%
            itemStyle: {
              normal: {
                // 配置箱体的样式
                color: {
                  type: "linearGradient",
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    { offset: 0, color: "rgba(88, 122, 250, 0.3)" }, // 0% 处的颜色
                    { offset: 1, color: "rgba(0, 78, 255, 0.7)" }, // 100% 处的颜色
                  ],
                  global: false, // 缺省为 false
                },
                borderColor: "rgba(0, 78, 255, 0.3)", // 箱体边框的颜色
                borderWidth: 1, // 箱体边框的宽度
              },
            },
            splitNumber: 1, // 控制箱体分割的数量
            tooltip: {
              formatter: function (param) {
                return [
                  "最高薪资: " + param.data[5],
                  "最低薪资: " + param.data[1],
                ].join("<br/>");
              },
            },
          },
        ],
      };
      // 深拷贝 不要影响原来的对象
      let tempOption = Object.assign({}, option);

      let tempSeries = [];

      this.chartData.city.forEach((item, index) => {
        tempSeries.push(option.series[index]);
      });
      this.chartData.city.forEach((item, index) => {
        if (tempSeries[index]) {
          tempSeries[index].name = this.chartData.city[index].name;
        }
      });
      tempOption.series = tempSeries;
      tempOption && this.myChart.setOption(tempOption);

      window.addEventListener("resize", () => {
        if (this.myChart) {
          this.myChart.resize();
        }
      });
    },
    onRegionChange(val) {
      this.selectedRegionList = [];
      //console.log("onRegionChange", val);
      val.forEach((item) => {
        this.selectedRegionList.push(item.split("-")[0]);
      });
      if (this.isSetDeaultRegion) {
        this.isSetDeaultRegion = false;
        return;
      }
      this.fetchData();
    },
    handleDateChange(val) {
      // //console.log("触发获取！！！111", this.isSetDeaultTime);
      if (this.isSetDeaultTime) {
        this.isSetDeaultTime = false;
        return;
      }
      this.pickerMinDate = null;
      // //console.log("触发获取！！！222");

      this.fetchData();
    },
    averageCitySalary(values) {
      let salary = 0;
      values.forEach((item, index) => {
        salary = salary + item;
      });

      if (values.length > 0) {
        const result = salary / values.length;
        return result.toFixed(1);
      } else {
        return "保密";
      }
    },
    handleKnowClick() {
      const userInfo = JSON.parse(localStorage.getItem("userInfo")); //OA的userInfo和SaaS登录的userInfo不一样
      const oaId = "";
      if (userInfo && userInfo.user_source_id) {
        oaId = userInfo.user_source_id;
      }
      const params = {
        positionId: this.$route.query.id,
        positionName: this.$route.query.name,
        layerId: "85",
        layerName: "薪酬变化趋势",
        personId: localStorage.getItem("personId") || "",
        oaId: oaId,
      };
      // console.log("----薪酬变化趋势---handleKnowClick--params", params);
      reportLackDataPosition(params).then((response) => {
        if (response.code == 200) {
          this.$message.success("已成功提交");
        } else {
          this.$message.error(res.status_desc);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.wrapper {
  width: 100%;
}

.chartMain {
  display: flex;
  align-items: center;
  padding-bottom: 15px;
  .empty {
    margin: auto;
    ::v-deep .el-empty__image {
      width: 150px;
    }
  }
}
.regionLineChart {
  display: flex;
  align-items: center;
}
.regionLineDesc {
  display: flex;
  flex: 0.3;
  flex-wrap: wrap;
  // width: 400px;
  justify-content: left;
  align-content: center;
  margin: 10px;
}

.regionLineDescItem {
  margin: 10px 0px;
  width: 45%;
}
.descTitle {
  color: #555;
  font-size: 15px;
}
.descNum {
  display: flex;
  align-items: baseline;
  color: #1b78ff;
  font-size: 24px;
  font-weight: bold;
  margin-top: 22px;
  font-family: ddin;
}
.rmb {
  font-size: 18px;
}
.h100 {
  flex: 0.7;
  height: 27vw;
  width: 100%;

  min-width: 615px;
  min-height: 240px;
}
::v-deep .el-date-editor {
  background: #fafcfe;
  border-radius: 4px;
  border: 1px solid #e4edf8;
}
::v-deep .el-form-item__label {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  line-height: 22px;

  display: flex;
  align-items: center;
  justify-content: center;
  height: 27px;
  min-width: 82px !important;
}
::v-deep .el-form-item {
  margin-bottom: 6px;
}
::v-deep .el-form-item:last-of-type {
  margin-bottom: 0px;
}
::v-deep .el-form-item__label-wrap {
  margin-left: 0px !important;
}
.search-container {
  display: flex;
  align-items: center;
}
</style>
